<?php
/**
 * Created by PhpStorm.
 * User: yanbin
 * Date: 2021/5/8
 * Time: 5:56 PM
 */

/**
 * 密码加密
 */
if (!function_exists('md5Pwd')) {
    function md5Pwd($pwd = '', $salt = '')
    {
        return md5($pwd . md5($salt));
    }
}
/**
 * 简单的参数过滤
 */
if (!function_exists('val')) {
    function val($val, $type = 0)
    {
        $val = trim($val);
        if ($val == '') {
            return '';
        }
        if (!is_string("$val")) {
            return '';
        }

        switch ($type) {
            case 0:
                return addslashes(htmlspecialchars($val, ENT_QUOTES));
                break;
            case 1:
                return intval($val);
                break;
            case 2:
                return $val;
                break;
            default :
                break;
        }
    }
}


/**
 * 返回值输出
 * return $status请求状态［0请求失败 1请求成功］ $msg请求结果说明 $data请求结果 $errCode失败错误码
 **/
if (!function_exists('output')) {
    function output($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        return response()->json(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
    }
}
/**
 * 原生
 * 返回值输出
 */
if (!function_exists('nativeOutput')) {
    function nativeOutput($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        echo json_encode(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
        die();
    }
}

/**
 * return $status请求状态［0请求失败 1请求成功］ $msg请求结果说明 $data请求结果 $errCode失败错误码
 */
if (!function_exists('outputJson')) {
    function outputJson($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        return json_encode(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
    }
}

/**
 * 生成短信随机码
 */
if (!function_exists('generateSmsCode')) {
    function generateSmsCode()
    {
        return rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
    }
}

/**
 * 设置cookie
 * data 的 key 作为 cookie 的 key, data 的 value 作为 cookie 的 value
 **/
if (!function_exists('setCookieData')) {
    function setCookieData($data = array())
    {
        foreach ($data as $key => $val) {
            \Cookie::queue($key, $val, 60 * 24 * 365);
        }
        return true;
    }
}
/**
 * 销毁cookie, value 为cookie 的key
 */
if (!function_exists('unsetCookieData')) {
    function unsetCookieData($data = array())
    {
        foreach ($data as $val) {
            \Cookie::queue($val, null, -1);
        }
        return true;
    }
}

/**
 * 创建随机码
 */
if (!function_exists('createCode')) {
    function createCode($namespace, $length)
    {
        static $gUid = '';
        $uid = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $hash = strtoupper(hash('ripemd128', $uid . $gUid . md5($data)));
        $rand = rand(0, 5);
        $gUid = substr($hash, $rand, $length);
        return $gUid;
    }
}

/**
 * 回调统一日志
 */
if (!function_exists('logRecord')) {
    function logRecord($path, $word = '')
    {
        $logPath = LOG_PATH . $path;
        if (!is_dir($logPath)) {
            mkdir($logPath);
        }
        $file = $logPath . DIRECTORY_SEPARATOR . date('Y_m_d') . '.log';
        $fp = fopen($file, "a");
        flock($fp, LOCK_EX);
        fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}
/**
 * 获取登录者信息
 */
if (!function_exists('userInfo')) {
    function userInfo()
    {
        return $userInfo = request()->get('userInfoVerify');
    }
}

/**
 *  判断数组里面的键值对是不是全是空值
 */
if (!function_exists('arrayValueIsAllNull')) {
    function arrayValueIsAllNull($array)
    {
        if (empty($array)) {
            return true;
        }
        foreach ($array as $item) {
            if (!empty($item)) {
                return false;
            }
        }
        return true;
    }
}

// 验证手机号
if (!function_exists('isMobile')) {
    function isMobile($mobile)
    {
        if (preg_match("/^1[3-9]{1}[0-9]{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}


/**
 * 过滤下空格输入
 */
if (!function_exists('space')) {
    function space($value)
    {
        $oldChar = array(" ", "　", "\t", "\n", "\r");
        $newChar = array("", "", "", "", "");
        $value =  preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","",str_replace($oldChar,$newChar,$value));

        return $value;
    }
}
/**
 *  登录用的加密token
 */
if (!function_exists('getToken')) {
    function getToken($uid, $mobile)
    {
        return md5($uid . md5($mobile . 'login2017wenda'));
    }
}

/**
 * 递归构建树形菜单
 *
 * @param array $nodes
 * @param int $parentId
 * @param string $parentString
 * @param string $childrenString
 *
 * @return array
 */
if (!function_exists('build_nested_array')) {
    function build_nested_array(array $nodes = [], $parentId = 0, $parentString = 'parent_id', $childrenString = 'children')
    {
        $branch = [];
        foreach ($nodes as $k => $node) {
            if ($node->$parentString == $parentId) {
                $children = build_nested_array($nodes, $node->id, $parentString, $childrenString);
                if ($children) {
                    $node->$childrenString = $children;
                }
                $branch[] = $node;
            }
        }
        return $branch;
    }
}

/**
 * 断点打印用于测试
 */
if (!function_exists('xx')) {
    function x($data = '')
    {
        $site = debug_backtrace();
        $data = print_r($data, true);
        echo "<strong>{$site[0]['file']}</strong>";
        echo "(line<strong>{$site[0]['line']}</strong>)\n<pre>\n";
        echo "{$data}\n</pre>\n";
        exit();
    }
}
//PHP stdClass Object转array
if (!function_exists('object_array')) {
    function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }
}
//pdo链接外部数据正式库
if (!function_exists('manage_pdo')) {

    function manage_pdo()
    {
        $dbms = 'mysql';     //数据库类型
        $host = 'rm-2zed37jb20of8e7x5.mysql.rds.aliyuncs.com'; //数据库主机名
        $dbName = 'schema';    //使用的数据库
        $user = 'schema_db';      //数据库连接用户名
        $pass = 'Minddna@2019';          //对应的密码
        $dsn = "$dbms:host=$host;dbname=$dbName";
        $db = new \PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
        return $db;
    }
}
//pdo链接外部数据测试库
if (!function_exists('test_pdo')) {

    function test_pdo()
    {
        $dbms = 'mysql';     //数据库类型
        $host = 'rm-2zed37jb20of8e7x5vo.mysql.rds.aliyuncs.com'; //数据库主机名
        $dbName = 'survey';    //使用的数据库
        $user = 'shijiazhuang_xinzhi_db';      //数据库连接用户名
        $pass = '108JFNEMWMVR';          //对应的密码
        $dsn = "$dbms:host=$host;dbname=$dbName";
        $db = new \PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
        return $db;
    }

    /**
     * 返回json  $options = JSON_FORCE_OBJECT 使用非关联数组时输出一个对象
     */
    if (!function_exists('responseJson')) {
        function responseJson($data = '', int $code = 200, string $message = '', bool $success = true)
        {
            $data = [
                'success' => $success,
                'message' => $message,
                'code' => $code,
                'data' => $data
            ];
            return response()->json($data);
        }
    }
    /**
     * json解析
     * @param string
     */
    if (!function_exists('jsonDecode')) {
        function jsonDecode(string $str = '')
        {
            $arr = json_decode($str, true);
            if ($arr) {
                return $arr;
            } else {
                return $str;
            }
        }
    }
    /**
     * 生成签名，$args为请求参数，$key为私钥
     * @param $args
     * @param $key
     * @return string
     */
    if (!function_exists('makeSignature')) {

        function makeSignature($args, $key)
        {
            if (isset($args['sign'])) {
                $oldSign = $args['sign'];
                unset($args['sign']);
            } else {
                $oldSign = '';
            }
            // 1. 对加密数组进行字典排序 防止因为参数顺序不一致而导致下面拼接加密不同
            ksort($args);
            $requestString = '';
            foreach ($args as $k => $v) {
                $requestString .= $k . '=' . urlencode($v);
            }
            $newSign = hash_hmac("md5", strtolower($requestString), $key);
            return $newSign;
        }
    }
    /**
     * curl 请求
     * @param $url
     * @param $params
     * @param int $timeout
     * @return bool|string
     */
    if (!function_exists('create_curl')) {
        function create_curl($url, $params, $timeout = 120)
        {
            //初始化curl
            $ch = curl_init();
            // 设置curl允许执行的最长秒数
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_URL, $url);
            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //设置头文件的信息作为数据流输出
            curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            //设置为post方式请求
            curl_setopt($ch, CURLOPT_POST, 1);
            //添加参数
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            //关闭请求资源
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }
    }
    /**
     * 发起请求
     * @param $url
     * @param int $timeout
     * @return mixed
     */
    if (!function_exists('doGet')) {
        function doGet($url, $timeout = 5)
        {
            //启动一个CURL会话
            $ch = curl_init();
            // 设置curl允许执行的最长秒数
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            // 获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_URL, $url);
            // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            // 执行操作
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        }
    }
    /**
     * 导出excel信息
     */
    if (!function_exists('exportExcelInfo')) {
        function exportExcelInfo($title, $data, $fileName = 'xxxx.xlsx')
        {
            @ini_set('memory_limit', '2048M');
            @set_time_limit(0);

//        $data = [
//            [1, 'jack', 10],
//            [2, 'mike', 12],
//            [3, 'jane', 21],
//            [4, 'paul', 26],
//            [5, 'kitty', 25],
//            [6, 'yami', 60],
//        ];
//
//        $title = ['编号', '姓名', '年龄'];

            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            //设置工作表标题名称
            $name = empty($fileName)?"工作表格":$fileName;
            $worksheet->setTitle($name);

            //表头
            //设置单元格内容
            foreach ($title as $key => $value) {
                $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
            }

            $row = 2; //从第二行开始
            foreach ($data as $item) {
                $column = 1;

                foreach ($item as $value) {
                    $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                    $column++;
                }
                $row++;
            }
            //2.输出到浏览器
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer->save('php://output');
            //释放
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);

        }

    }
    /**
     * 简单的参数过滤
     */
    if (!function_exists('val')) {
        function val($val, $type = 0)
        {
            $val = trim($val);
            if ($val == '') {
                return '';
            }
            if (!is_string("$val")) {
                return '';
            }
            switch ($type) {
                case 0:
                    return addslashes(htmlspecialchars($val, ENT_QUOTES));
                    break;
                case 1:
                    return intval($val);
                    break;
                case 2:
                    return $val;
                    break;
                default :
                    break;
            }
        }
    }
    /**
     * csv 导出数据
     */
    if (!function_exists('exportCsvInfo')) {
        function exportCsvInfo($title, $data, $fileName = 'parent.csv')
        {
            @ini_set('memory_limit', '2048M');
            @set_time_limit(0);
            ob_start();
            if (!$title || !$data || !is_array($data)) {
                return false;
            }
            try {
                setlocale(LC_ALL, 'en_US.UTF-8');
                // 输出 Excel 文件头
                $fileName = empty($fileName) ? date('YmdHis') : $fileName . '_' . date('YmdHis');
                $fileName = $fileName . ".csv";
                $string = "";
                $string .= implode(',', $title) . PHP_EOL;
                foreach ($data as $key => $value) {

                    foreach ($value as $k => $val) {
                        $value[$k] = empty($val) ? ' ' : val($val) . " ";
                    }
                    $string .= implode(",", $value) . PHP_EOL; //用英文逗号分开
                }


                ob_end_clean();
                header("Content-type:text/csv");
                header("Content-Disposition:attachment;filename=" . $fileName);
                header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
                header('Expires:0');
                header('Pragma:public');
                echo iconv('UTF-8', 'GBK//IGNORE', $string);

                exit;
            } catch (Exception $e) {
                return $e->getMessage();
            }
        }
    }

}
